﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Mindfor.Web
{
	/// <summary>
	///	Represents attribute which replaces HttpStatusCodeResult to ViewResult with name {HttpStatusCode}.cshtml
	/// </summary>
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
	public class HttpStatusCodeReplaceAttribute : FilterAttribute, IActionFilter
	{
		/// <summary>
		/// Invoked after action has exeecuted. If filterContext is HttpStatusResult 
		/// </summary>
		public void OnActionExecuted(ActionExecutedContext filterContext)
		{
			HttpStatusCodeResult result = filterContext.Result as HttpStatusCodeResult;
			if (result != null)
			{
				string viewName = result.StatusCode.ToString();
				ViewEngineResult viewEngineResult = ViewEngines.Engines.FindView(filterContext.Controller.ControllerContext, viewName, null);
				if (viewEngineResult.View != null)
				{
					filterContext.Result = new ViewResult() { View = viewEngineResult.View, ViewData = filterContext.Controller.ViewData, TempData = filterContext.Controller.TempData };
				}
			}
		}

		/// <summary>
		/// Invoked before action has exeecuted. Empty for this attribute.
		/// </summary>
		public void OnActionExecuting(ActionExecutingContext filterContext)
		{
		}
	}
}